package concurrent.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author: 黄嘉振
 * @create: 2023/6/15 17:09
 * @description:
 **/
public class SemaphoreDemo {
    public static void main(String[] args) {
        SemaphoreTask task = new SemaphoreTask();
        for (int i = 0; i < 10; i++) {
            new Thread(task, String.valueOf(i)).start();
        }
    }
}
class SemaphoreTask implements Runnable {
    // 申请了4个准⼊，那么将会以4个线程⼀组为单位进⾏执⾏输出
    private Semaphore semaphore = new Semaphore(4);

    @Override
    public void run() {
        try {
            semaphore.acquire();
            TimeUnit.SECONDS.sleep(2);
            System.out.println(System.currentTimeMillis() / 1000 + " , " + Thread.currentThread().getName() + " 执行完毕！");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            semaphore.release();
        }
    }
}
